<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <!-- 财务信息 -->
  <view class="Mall4j page-store-settings-financial">
    <view
      v-if="paySettlementType !== 1"
      class="head"
    >
      <view class="tit">
        结算账户
      </view>
      <view class="tips">
        （已添加<text class="stress">
          {{ settlementAccounts.length }}
        </text>个账户，
        最多可添加<text class="stress">
          {{ maxNum }}
        </text>个）
      </view>
    </view>
    <view
      v-else
      class="allinpay-head"
    >
      <view class="tit">
        <text>结算账户</text>
        <view class="alinpay-btns">
          <view
            v-if="!(legalAcctProtocolNo&&acctProtocolNo)"
            class="text-btn"
            @tap="onShowSignDialog"
          >
            签订协议
          </view>
          <view
            class="text-btn"
            @click="onShowMobileDialog"
          >
            {{ mobile ? '解除绑定' : '绑定手机' }}
          </view>
        </view>
      </view>
      <view class="tips">
        已添加
        <text class="stress">
          {{ cardNumber }}
        </text>
        个结算账户，最多可添加
        <text class="stress">
          10
        </text>
        个结算账户
        <text>
          ，
          <text class="stress">
            1
          </text>
          个法人账户
        </text>
        <text v-if="mobile">
          ，绑定手机号：<text class="stress">
            {{ mobile }}
          </text>
        </text>
      </view>
    </view>

    <!-- 账户列表 -->
    <view class="account-list">
      <view
        v-for="item in settlementAccounts"
        :key="item.cardNo"
        class="account-item"
        @tap="onPutShopBankCard(item.shopBankCardId)"
      >
        <view class="ac-top">
          {{ item.bankName }}<text class="tag">
            {{ item.isDefault ? "（默认账户）" : "" }}
          </text>
        </view>
        <view class="ac-bottom">
          <view class="account-num">
            {{ item.cardNo }}
          </view>
          <view class="account-info">
            <view class="account-info-content">
              <view class="name">
                {{ item.recipientName }}
                <view
                  v-if="paySettlementType===1 && item.bankCardPro===0"
                  class="legalTip"
                >
                  法人
                </view>
              </view>
              <text>{{ item.openingBank }}</text>
            </view>
            <view class="operating-btn">
              <view
                v-if="paySettlementType===1 && item.bankCardPro===0"
                class="isDefault unbind-btn"
                @tap.stop="onUnbindBankCard(item.cardNo,item.shopBankCardId)"
              >
                解绑
              </view>
              <view v-if="baseInfoForm.shopStatus !== 5">
                <view
                  v-if="item.isDefault"
                  :class="{'m-disable':!$isAuthorities('shop:shopBankCard:noDefault')}"
                  class="isDefault"
                  @tap.stop="onSetNotDefault(item.shopBankCardId)"
                >
                  取消默认
                </view>
                <view
                  v-if="!item.isDefault"
                  :class="{'m-disable':!$isAuthorities('shop:shopBankCard:default')}"
                  class="isDefault"
                  @tap.stop="onSetDefault(item.shopBankCardId)"
                >
                  设为默认
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view
      v-if="settlementAccounts.length === 5 && paySettlementType !== 1"
      class="warm-tips"
    >
      提示：账户添加已达到上限，请先删除其中一个再添加。
    </view>

    <!-- 添加 -->
    <view
      v-if=" $isAuthorities('shop:shopBankCard:save')&&(settlementAccounts.length < 5 && baseInfoForm.shopStatus !== 5 || (paySettlementType === 1 && (legalCardNumber<1 || cardNumber<10)))"
      class="add-btn"
      @tap="onAddAccount"
    >
      + 添加新账户
    </view>

    <!-- 绑定/解绑手机 -->
    <mobule-add-or-update
      v-if="mobileDialogVisible"
      ref="mobileAddOrUpdateRef"
      :is-have-mobile="!!mobile"
      @refresh-data-form="onQueryCompany"
    />

    <!-- 签约协议 -->
    <sign-acct-protocol
      v-if="signDialogVisible"
      ref="signAcctProtocolRef"
      :acct-protocol-no="acctProtocolNo"
      :legal-acct-protocol-no="legalAcctProtocolNo"
      :mobile="mobile"
      :legal-card-number="legalCardNumber"
    />
  </view>
</template>

<script setup>
import MobuleAddOrUpdate from '../../components/mobule-add-or-update/mobile-add-or-update.vue'
import SignAcctProtocol from '../../components/sign-acct-protocol/sign-acct-protocol.vue'

const paySettlementType = uni.getStorageSync('bbcPaySettlementType')

const $isAuthorities = util.isAuthorities
// 结算账户数目最大值
const maxNum = 5
// 账户列表
const settlementAccounts = ref([])
const baseInfoForm = ref({
  shopStatus: 0
})
let companyInfoProcessStatus = null
onShow(() => {
  onGetShopBankCardList()
  onGetShopDetailnfo()

  if (paySettlementType === 1 && companyInfoProcessStatus !== 0 && companyInfoProcessStatus !== 3) {
    // 查询企业信息
    onQueryCompany()
  }
})

const acctProtocolNo = ref('') // 签约提现协议号
onLoad((options) => {
// #ifdef H5
  if (paySettlementType !== 1) {
    return
  }
  // 获取内存中的签约编号
  const acctProtocolNo = uni.getStorageSync('bbcAllinpayAcctProtocolNo')
  // 以下代码为H5页面签约成功执行, 小程序在App.vue的onShow中,APP则在单独的页面redirect.vue中
  // 如果本次签约和存储中的签约编号不一致，则需要提示签约成功并更新签约编号，否则不提示，避免重复提示签约成功
  if (Number(options.isSignSuccess) === 1 && options.bizContent && acctProtocolNo !== options.bizContent.acctProtocolNo) {
    uni.showToast({
      title: '签约成功',
      icon: 'none',
      duration: 1000
    })
    // 上方已经重新获取通联会员信息，所以不用再次请求
    uni.setStorageSync('bbcAllinpayAcctProtocolNo', options.bizContent.acctProtocolNo)
  } else if (Number(options.isSignSuccess) === 0) {
    uni.showToast({
      title: '签约失败',
      icon: 'none',
      duration: 1000
    })
  }
  // #endif
})

/**
 * 获取店铺信息
 */
const legalAcctProtocolNo = ref('') // 法人签约提现协议号
const onGetShopDetailnfo = () => {
  const params = {
    url: '/shop/shopDetail/info',
    method: 'GET'
  }
  http.request(params).then(({ data: res }) => {
    baseInfoForm.value = res
    companyInfoProcessStatus = res.companyInfoProcessStatus
  })
}
/**
   * 添加结算账户
   */
const onAddAccount = () => {
  if (paySettlementType === 1) {
    uni.redirectTo({
      url: '/package-settings/pages/allinpay-store-account/allinpay-store-account'
    })
    return
  }
  uni.redirectTo({
    url: '/package-settings/pages/store-settings-account/store-settings-account'
  })
}
/**
 * 获取店铺下的账户列表
 */
const legalCardNumber = ref(0) // 法人账户数量
const cardNumber = ref(0) // 非法人账户数量
const onGetShopBankCardList = () => {
  const params = {
    url: '/shop/shopBankCard/getShopBankCardList',
    method: 'GET'
  }
  uni.showLoading({
    mask: true
  })
  http.request(params).then(({ data: res }) => {
    if (paySettlementType === 1 && res && res.length > 0) {
      legalCardNumber.value = res.filter(item => item.bankCardPro === 0).length
      cardNumber.value = res.length - legalCardNumber.value
    }
    settlementAccounts.value = res
    uni.hideLoading()
  })
}
/**
 * 编辑账户信息
 *  @param {Number} shopBankCardId  账户id
 */
const onPutShopBankCard = (shopBankCardId) => {
  if (paySettlementType === 1) {
    return
  }
  uni.redirectTo({
    url: '/package-settings/pages/store-settings-account/store-settings-account?id=' + shopBankCardId + '&isNotEdit=' + (baseInfoForm.value.shopStatus === 5 ? 1 : 0)
  })
}
/**
 * 设为默认账户
 * @param {Number} shopBankCardId  账户id
 */
const onSetDefault = (shopBankCardId) => {
  http.request({
    url: '/shop/shopBankCard/setDefault',
    method: 'PUT',
    data: { shopBankCardId }
  }).then(() => {
    uni.hideToast()
    uni.showToast({
      title: '设置成功',
      success: () => {
        onGetShopBankCardList()
      }
    })
  })
}
/**
 * 取消默认账户
 * @param {Number} shopBankCardId  账户id
 */
const onSetNotDefault = (shopBankCardId) => {
  http.request({
    url: '/shop/shopBankCard/setNotDefault?shopBankCardId=' + shopBankCardId,
    method: 'PUT'
  }).then(() => {
    uni.hideToast()
    uni.showToast({
      title: '设置成功',
      success: () => {
        onGetShopBankCardList()
      }
    })
  })
}

// 查询企业信息（通联）
const mobile = ref('')
const onQueryCompany = () => {
  http.request({
    url: '/shop/allinpay/company/getCompanyInfo',
    method: 'get'
  }).then(({ data }) => {
    mobile.value = data.phone
    acctProtocolNo.value = data.acctProtocolNo // 签约信息
    legalAcctProtocolNo.value = data.legalAcctProtocolNo // 签约信息
  })
}

// 绑定/解绑手机号
const mobileAddOrUpdateRef = ref(null)
const mobileDialogVisible = ref(false)
const onShowMobileDialog = () => {
  mobileDialogVisible.value = true
  nextTick(() => {
    mobileAddOrUpdateRef.value.init(mobile.value)
  })
}

// 签约协议
const signAcctProtocolRef = ref(null)
const signDialogVisible = ref(false)
const onShowSignDialog = () => {
  signDialogVisible.value = true
  onQueryCompany()
  nextTick(() => {
    signAcctProtocolRef.value.init()
  })
}
// 解绑银行卡
const onUnbindBankCard = (cardNo, shopBankCardId) => {
  uni.showModal({
    title: '提示',
    content: '是否解绑法人账号?',
    success: (modalRes) => {
      if (modalRes.confirm) {
        http.request({
          url: '/shop/allinpay/company/unbindBankCard',
          method: 'PUT',
          data: { cardNo, shopBankCardId }
        }).then(() => {
          uni.hideToast()
          uni.showToast({
            title: '解绑成功',
            success: () => {
              setTimeout(() => {
                onGetShopBankCardList()
              }, 1500)
            }
          })
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
@use './store-settings-financial.scss';
</style>
